<template>
  <basic-container class="menu-container">
    <div class="menu-header">
      <ArrowLeftBold
        @click="handleBack"
        width="24"
        height="24"
        style="padding-top: 4px; cursor: pointer"
        title="返回"
      />
      <p class="menu-title">{{ trialForm.name }}</p>
    </div>
    <div class="menu-content">
      <avue-form
        :option="option"
        v-model="form"
        @submit="handleSubmit"
        @reset-change="handleReset"
      ></avue-form>
      <div class="select-name">
        <span style="font-size: 16px; color: #3c8dbc">已选变量项：</span>
        <span
          style="font-size: 14px; color: black; margin-right: 10px"
          v-for="(item, index) in selectNameArray"
          :key="index"
          >{{ item }}；</span
        >
      </div>
      <div class="crf-tree-detail">
        <div class="crf-tree">
          <el-tree
            :props="props"
            :load="loadNode"
            lazy
            node-key="id"
            :highlight-current="true"
            @node-expand="handleNodeExpand"
            @node-click="handleNodeClick"
          />
        </div>
        <div class="crf-detail">
          <span style="font-size: 16px; color: black">在左侧选择CRF表，以下进行变量挑选。</span>
          <div class="crf-detail-content">
            <VFormRender
              :form-json="formJson"
              :form-data="formData"
              :option-data="optionData"
              ref="vFormRef"
              @formChange="onFormDataChange"
            >
            </VFormRender>
          </div>
        </div>
      </div>
    </div>
  </basic-container>
</template>
<script setup>
import { Plus, DocumentChecked } from '@element-plus/icons-vue';
import {
  getList,
  getDetail,
  add,
  update,
  remove,
} from '@/api/variablemanagement/variableManagement';
import { getTrialDetail, groupListOfTrial } from '@/api/trial/trial';
import { getCrfDetail } from '@/api/crf/crf.js';
import { treeWithCrf } from '@/api/group/group';
import VFormRender from '@/components/form-render/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, reactive, computed, onMounted, nextTick, watch, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const store = useStore();
const routerQuery = ref({});
routerQuery.value = route.query;

const formJson = ref({});
const vFormRef = ref(null);
const formData = ref({});
const optionData = ref({});

let option = ref({
  menuSpan: 6,
  menuPosition: 'right',
  disabled: false,
  submitBtn: true,
  emptyBtn: true,
  column: [
    {
      label: '变量名称',
      prop: 'name',
      type: 'input',
      rules: [
        {
          required: true,
          message: '请输入变量名称',
          trigger: 'blur',
        },
      ],
      span: 9,
    },
    {
      label: '数据类型',
      prop: 'dataType',
      type: 'select',
      dicUrl: '/api/blade-system/dict-biz/dictionary?code=variable_management_data_type',
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      filterable: true,
      overHidden: true,
      span: 9,
    },
  ],
});
let form = ref({});

let groupCrfObj = ref({});
let selectNameArray = ref([]);

const sendCheckedList = computed(() => store.getters.checkedList);
watch(
  () => sendCheckedList.value,
  (newVal, oldVal) => {
    if(!routerQuery.value.variableId){
      // 执行你的处理逻辑
      watchChecked(newVal);
    }
  },
  { deep: true } // 深度监听对象/数组变化
);
const watchChecked = newVal => {
  selectNameArray.value = newVal.map(id => {
    return `${id}_${groupCrfObj.value.crfName}_${groupCrfObj.value.phaseTitle}_${groupCrfObj.value.groupName}`;
  });
};

const handleSubmit = (form, done) => {
  let checkedList = JSON.parse(localStorage.getItem('checkedList'));
  // 定义 selectIds 和 selectNames 变量
  let selectIds = [];
  let selectNames = [];

  // 遍历问题id数组，拼接格式
  checkedList.forEach(questionId => {
    // 拼接 selectIds
    selectIds.push(
      `${questionId}_${groupCrfObj.value.crfId}_${groupCrfObj.value.phaseId}_${groupCrfObj.value.groupId}`
    );

    // 拼接 selectNames
    selectNames.push(
      `${questionId}_${groupCrfObj.value.crfName}_${groupCrfObj.value.phaseTitle}_${groupCrfObj.value.groupName}`
    );
  });

  // 将结果合并成字符串
  form.selectIds = selectIds.join('|');
  form.selectNames = selectNames.join('|');
  form.trial = routerQuery.value.trialId;
  form.groupId = groupCrfObj.value.groupId;
  form.type = routerQuery.value.btnType;
  done();
  add(form).then(res => {
    ElMessage({
      type: 'success',
      message: '操作成功!',
    });
    setTimeout(() => {
      done();
      handleBack();
    }, 500);
  });
};
const handleReset = () => {
  store.commit('SET_CHECKED_LIST', []);
  localStorage.removeItem('checkedList');
};

onMounted(() => {
  if (routerQuery.value.variableId) {
    getDetail(routerQuery.value.variableId).then(res => {
      const DATA = res.data.data;
      form.value = DATA;
      initFormObject(form.value);
    });
  }
  option.value.disabled = false;
  option.value.submitBtn = true;
  option.value.emptyBtn = true;
  if (routerQuery.value.variableView) {
    option.value.disabled = true;
    option.value.submitBtn = false;
    option.value.emptyBtn = false;
  }
});

// 将
const initFormObject = form => {
  // 拆分 selectIds 和 selectNames 字符串
  const selectIdArray = form.selectIds.split('|');
  selectNameArray.value = form.selectNames.split('|');

  // 获取问题 ID 数组
  const questionIds = selectIdArray.map(item => item.split('_')[0]);

  // 获取通用信息对象
  const commonData = {
    groupId: selectIdArray[0].split('_')[3],
    phaseId: selectIdArray[0].split('_')[2],
    phaseTitle: selectNameArray.value[0].split('_')[2],
    crfId: selectIdArray[0].split('_')[1],
    crfName: selectNameArray.value[0].split('_')[1],
  };
  store.commit('SET_CHECKED_LIST', questionIds);
  localStorage.setItem('checkedList', JSON.stringify(questionIds));
};

// 树形配置
const props = {
  label: 'name', // 节点显示文本字段
  children: 'children', // 子节点字段
  isLeaf: 'isLeaf', // 判断是否为叶子节点
};

// 加载节点方法
const loadNode = (node, resolve) => {
  if (node.level === 0) {
    // 加载根节点（研究组/测试组）
    groupListOfTrial(routerQuery.value.trialId).then(res => {
      const groups = res.data.data.map(group => ({
        id: group.id,
        name: group.name,
        isLeaf: false, // 组节点需要继续加载
        type: 'group',
      }));
      resolve(groups);
    });
  } else if (node.level === 1) {
    // groupCrfObj.value.groupId = node.data.id;
    // 加载阶段节点
    treeWithCrf(node.data.id).then(res => {
      const phases = res.data.data.map(phase => ({
        id: phase.id,
        name: phase.title,
        isLeaf: !phase.crfList?.length, // 根据是否有CRF判断是否为叶子
        type: 'phase',
        rawData: phase, // 保留原始数据
      }));
      resolve(phases);
    });
  } else if (node.level === 2) {
    // 加载CRF列表
    const crfs = node.data.rawData.crfList.map(crf => ({
      id: crf.id,
      name: crf.crfName,
      isLeaf: true, // 末级节点
      type: 'crf',
      crf: crf.crf,
    }));
    resolve(crfs);
  }
};
const handleNodeClick = (nodeData, nodeObj, event) => {
  // 判断是否为组点击
  if (nodeObj.level === 1) {
    groupCrfObj.value.groupId = nodeData.id;
    groupCrfObj.value.groupName = nodeData.name;
  }
  // 判断是否为阶段点击
  if (nodeObj.level === 2) {
    groupCrfObj.value.phaseId = nodeData.id;
    groupCrfObj.value.phaseTitle = nodeData.name;
  }
  // 判断是否为叶子节点
  if (nodeObj.isLeaf) {
    // store.commit('SET_SELECT_COMPONENT_DIALOG', true);
    groupCrfObj.value.crfId = nodeData.crf;
    groupCrfObj.value.crfName = nodeData.name;
    localStorage.setItem('sendDisabledBoole',false); 
    if(selectNameArray.value.length > 0 && routerQuery.value.btnType === '3'){
      localStorage.setItem('sendDisabledBoole',true); 
    }
    if (routerQuery.value.variableId) {
      initFormObject(form.value);
    }
    initGetCrfDetail(nodeData.crf);
  }
};
const handleNodeExpand = (data, node) => {
  // 判断是否为组点击
  if (node.level === 1) {
    groupCrfObj.value.groupId = data.id;
    groupCrfObj.value.groupName = data.name;
  }
  // 判断是否为阶段点击
  if (node.level === 2) {
    groupCrfObj.value.phaseId = data.id;
    groupCrfObj.value.phaseTitle = data.name;
  }
};

const initGetCrfDetail = async crfId => {
  const { data: res } = await getCrfDetail(crfId);
  if (res.code == 200) {
    formJson.value = JSON.parse(res.data.content);
    nextTick(() => {
      vFormRef.value.setFormJson(formJson.value);
    });
  }
};

// 返回
const handleBack = () => {
  delete routerQuery.value.variableId;
  delete routerQuery.value.variableView;
  store.commit('SET_CHECKED_LIST', []);
  localStorage.removeItem('checkedList');
  localStorage.removeItem('sendDisabledBoole');
  router.replace({
    path: '/trial/variable',
    query: {
      ...routerQuery.value,
    },
  });
};

const trialForm = ref({});
const initTrialDetail = async id => {
  let res = await getTrialDetail(id);
  trialForm.value = res.data.data;
};
onMounted(() => {
  if (routerQuery.value.trialId) {
    initTrialDetail(routerQuery.value.trialId);
  }
});
</script>
<style lang="scss" scoped>
.menu-container {
  ::v-deep .basic-container__card {
    height: 100%;
  }
  ::v-deep .el-card__body {
    height: 100%;
  }
  height: 100%;
  overflow-y: hidden;
}
.menu-header {
  width: 100%;
  height: auto;
  margin-bottom: 10px;
  padding-bottom: 20px;
  display: flex;
  align-items: center;
  border-bottom: 2px solid #ebeef5;
}
.menu-title {
  font-size: 28px;
  margin-top: 0;
  // margin-left: 10px;
  margin-bottom: 0;
}
.menu-content {
  width: 100%;
  height: calc(100% - 120px);
}
.select-name {
  width: auto;
  height: auto;
  padding: 20px 10px;
  padding-top: 0;
}
.crf-tree-detail {
  width: auto;
  height: calc(100% - 85px);
  display: flex;
}
.crf-tree {
  width: 40%;
  height: 100%;
  overflow-y: auto;
}
.crf-detail {
  width: 60%;
  height: 100%;
  padding-left: 20px;
  display: flex;
  flex-direction: column;
}
.crf-detail-content {
  flex: 1;
  margin-top: 20px;
  overflow-y: auto;
}
</style>